$(function () {
    getEchartsInfo();
    init_selectUser();
    /**初始化标签得内容**/
    $.post(ctx+"saleConfig/selectSaletag",{},function (r) {
        if (r.code == 0){
            var data = r.msg;
            $.each(data,function (index,val) {
                var div =  $(' <div class="text-left border-bottom-1"></div>');
                var fistdiv  ='<div class="border-bottom-1 p-t-3"><div class="checkbox m-0"><span class="m-r-15 m-l-5">'+val.parent.tagGroupName+'</span>\n' +
                    '<label><input type="checkbox" style="margin: 1px -20px 0px;" />不包含 <input type="hidden" value='+val.parent.tagSelect+' /></label></div></div>';
                div.append(fistdiv);
                var cc = $("<div class='m-t-5 p-3 text-left'><input type='hidden' value="+val.parent.tagSelect+" /></div>");
                $.each(val.children,function (i,v) {
                    cc.append('<button type="button" onclick="selectTagIscheck(this)" data-id="'+v.tagUuids+'" ' +
                        'class="btn btn-xs btn-link width-100 m-l-5 p-2 m-b-5 f-s-12 border-solid-g">'+v.tagName+'</button>');
                });
                div.append(cc);
                $("#selectTag").append(div);
            });
        }else{
            $JuXue.n_danger(r.msg);
        }
    });
    /**初始化时间选择**/
    $("#select_time span").html(moment().subtract("days",29).format("YYYY-MM-DD")+" - "+moment().format("YYYY-MM-DD"));
    $('#select_time').daterangepicker({
        timePicker: true, //显示时间
        timePicker24Hour: true, //时间制
        timePickerSeconds: true, //时间显示到秒
        startDate: moment().hours(0).minutes(0).seconds(0), //设置开始日期
        endDate: moment(new Date()), //设置结束器日期
        maxDate: moment(new Date()), //设置最大日期
        minDate: moment().add('year',-1), //设置最小日期
        "opens": "center",
        ranges: {
            '今天': [moment(), moment()],'昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            '上周': [moment().subtract(6, 'days'), moment()],
            '前30天': [moment().subtract(29, 'days'), moment()],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        showWeekNumbers: true,
        locale: {
            format: "YYYY-MM-DD HH:mm:ss", //设置显示格式
            applyLabel: '确定', //确定按钮文本
            cancelLabel: '取消', //取消按钮文本
            customRangeLabel: '自定义',
            daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
            monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                '七月', '八月', '九月', '十月', '十一月', '十二月'
            ],
            firstDay: 1
        },
    }).on('apply.daterangepicker', function(ev, picker) {
        var starttime = picker.startDate.format('YYYY-MM-DD');
        var endtime = picker.endDate.format('YYYY-MM-DD');
        $("#select_time span").html(starttime+" - "+endtime);
        $("#starttime").val(starttime);
        $("#endtime").val(endtime);
        //刷新列表
        getEchartsInfo();
    });
});
/**选择时间类型**/
function selectNySeletTimne(btn) {
    var data_cliak = $(btn).attr("data-click");
    if(data_cliak === "selft"){
        $("#select_time").removeClass("hidden");
        $("#starttime").val(moment().subtract("days",29).format("YYYY-MM-DD"));
        $("#endtime").val(moment().format("YYYY-MM-DD"));
    }else{
        $("#select_time").addClass("hidden");
        $("#starttime").val(data_cliak);
        $("#endtime").val('');
    }
    $("#timeRemove").find("button").each(function () {
        $(this).removeClass("btn-primary");
    });
    $(btn).addClass("btn-primary");
    //刷新列表
    getEchartsInfo();
}
/**点击其他标签选项卡**/
function selectTagByOther(btn) {
    $("#otherselect").find("a").each(function () {
        $(this).removeClass("btn-primary");
    });
    $(btn).addClass("btn-primary");
    //动态加载
    var project = $(btn).attr("data-click");
    $("#selecttagOnter").val(project);
    //刷新列表
    getEchartsInfo();
}
/**选择标签**/
function selectTagIscheck(btn) {
    var $parentcheck  = $(btn).parent();
    var isMultiInput = $parentcheck.children("input:first-child").val();
    if (isMultiInput == "1"){
        //多选
        var ishave = $(btn).hasClass("btn-primary");
        if (ishave) {
            $(btn).removeClass("btn-primary");
        }else{
            $(btn).addClass("btn-primary");
        }
    }else{
        //单选
        var ishave = $(btn).hasClass("btn-primary");
        if (ishave) {
            $parentcheck.find("button").each(function () {
                $(this).removeClass("btn-primary");
            });
        }else{
            $parentcheck.find("button").each(function () {
                $(this).removeClass("btn-primary");
            });
            $(btn).addClass("btn-primary");
        }
    }
}
/**确定标签**/
function labelSelectSure() {
    var div = $("#selectTag").children("div");
    //包含
    var selectids = new Array();
    var selectnames = new Array();
    //不包含
    var notselectids = new Array();
    var notselectnames = new Array();
    $.each(div,function (index,val) {
        var isChecked = $(this).find("input[type='checkbox']").eq(0).is(':checked');
        if (isChecked) {
            //如果选中 则表示不包含
            var btn = $(this).find("button");
            $.each(btn,function () {
                var isSelect = $(this).hasClass("btn-primary");
                if (isSelect){
                    var notselectid = $(this).attr("data-id");
                    var notselectname = $(this).text();
                    notselectids.push(notselectid);notselectnames.push(notselectname);
                }
            });
        }else{
            //包含
            var btn = $(this).find("button");
            $.each(btn,function () {
                var isSelect = $(this).hasClass("btn-primary");
                if (isSelect){
                    var selectid = $(this).attr("data-id");
                    var selectname = $(this).text();
                    selectids.push(selectid);selectnames.push(selectname);
                }
            });
        }
    });
    var length = selectids.length+notselectids.length;
    if(length > 5){$JuXue.n_danger("标签选择不能大于5个");return ;}
    else {if (length <= 0){$("#otherselect").show();}else{$("#otherselect").hide();}}
    $("#drownSelect").empty();
    $.each(selectnames,function (i,v) {
        $("#drownSelect").append('<a type="button" class="btn btn-link m-l-10 p-3 f-s-10 btn-primary ">'+v+'</a>');
    });
    $.each(notselectnames,function (i,v) {
        $("#drownSelect").append('<a type="button" class="btn btn-link m-l-10 p-3 f-s-10 btn-default">'+v+'</a>');
    });
    $("#labelselect").removeClass("open");
    $("#selectContion").val(selectids.join(","));
    $("#selectNotContion").val(notselectids.join(","));
    //刷新列表
    getEchartsInfo();
}
/**选择员工**/
function selectUserList(){
    $('#selectsaleUsers').removeClass('open');
    var allUser = $('#select_sale_user').jstree(true).get_selected(false);//获得整个树
    var usersArray = new Array();
    var nicknameArray = new Array();
    if (allUser.length > 0){
        //说明选择了人员
        $("#otherUserSelect").find("div").each(function () {
           var nickname = $(this).text();
           var users = $(this).attr("data-id");
            usersArray.push(users);
            nicknameArray.push(nickname);
        });
        $("#gerenyuanid").val(usersArray.join(","));
        $("#gerenyuanname").val(nicknameArray.join(","));
    }else{
        //没有选择人员
        $("#gerenyuanid").val("");
        $("#gerenyuanname").val("");
        $("#nouserSelect").addClass("btn-primary");
    }
    //刷新折线图
    getEchartsInfo();
}
/**初始化选择人员**/
function init_selectUser(){
    $.post(ctx+"dept/getUserAndDeptByTreeWhisRole",{},function (r) {
        var array  = r.msg;
        $("#select_sale_user").jstree({
            "core": {
                "multiple": true,//单选
                "data":array,
                "icon":false,
                "themes":{
                    "icons":false
                }
            },
            "checkbox" : {
                "keep_selected_style" : false
            },
            "plugins" : [ "wholerow", "checkbox" ]
        });
        // 获得点击节点的id
        $('#select_sale_user').on("changed.jstree", function (e, data) {
            var nodeid = data.node.id;
            var text = data.node.text;
            var action = data.action;;
            if (action == "deselect_node") {
                $("#otherUserSelect").find("div").each(function () {
                    var data_id = $(this).attr("data-id");
                    if (data_id == nodeid) $(this).remove();
                });
            }else{
                /**判断是不是超过 5个 超过5个则不能继续追加**/
                var divlength = $("#otherUserSelect").find("div");
                if(divlength.length >= 3){
                    $JuXue.n_danger("选择查询类型不能超过3个");
                    $("#select_sale_user").jstree("deselect_node",nodeid);
                    return;
                }else{
                    if(divlength.length >0){
                        var ble = false;
                        $("#otherUserSelect").find("div").each(function () {
                            var data_id = $(this).attr("data-id");
                            if (data_id == nodeid){ble = true;}
                        });
                        if(!ble){
                            var label = "<div class='label label-danger p-3 m-3 ' data-id='"+nodeid+"'>"+text+"</div>";
                            $("#otherUserSelect").append(label);
                        }
                    }else{
                        var label = "<div class='label label-danger p-3 m-3 ' data-id='"+nodeid+"'>"+text+"</div>";
                        $("#otherUserSelect").append(label);
                    }
                }
            }
        });
    });
}
/**获取折线图得数据**/
function getEchartsInfo(){
    var json = {
        userid   :   $("#gerenyuanid").val(),   //选择人员
        otherLabel: $("#selecttagOnter").val(),//其他标签
        label:      $("#selectContion").val(),//包含标签
        notLabel:   $("#selectNotContion").val(),//不包含标签
        beforeTime: $("#starttime").val(), //开始时间
        afterTime:  $("#endtime").val(),//结束时间
        nickname :  $("#gerenyuanname").val()
    };
    var benel = $("#paneldia").closest(".panel");
    if (!$(benel).hasClass("panel-loading")) {
        var c = $(benel).find("#paneldia .panel-body"),
            d = '<div class="panel-loader"><span class="spinner-small"></span></div>';
        $(benel).addClass("panel-loading"), $(c).prepend(d);
    }
    $.post("SaleManage/getCustomerIndex",json,function(r){
        if (r.code==0 ){
            var data = r.msg;
            init_cuaindex_statis(data.legend,data.series,data.xAxis);

            var array = data.table;
            $("#tbody").empty();
            $.each(array,function (index,val) {
                var tableNum = "<tr>\n" +
                "   <td >"+val.time+"</td>\n" +
                "   <td>"+val.add+"</td>\n" +
                "   <td >"+val.delete+"</td>\n" +
                "   <td><a href='#'>"+val.all+"</a></td>\n" +
                "</tr>";
                $("#tbody").append(tableNum);
            });
            $(benel).removeClass("panel-loading");
            $(benel).find("#paneldia .panel-loader").remove();
        }else{
            $JuXue.n_danger("加载图标失败");
        }
    });
    var ass = $("#expandManage").hasClass("height-full width-full m-0");
    if (ass){
        $("#paneldia").addClass("height-600");
    }else{
        $("#paneldia").removeClass("height-600");
    }
}

/**获取客户数据统计**/
function init_cuaindex_statis(legend,series,xaxis) {
    var myChart = echarts.init(document.getElementById('sale_customer'));
    var option = {
        title: {
            text: '客户总数走势图'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data:legend
        },
        grid: {
            left: '3%',
            right: '2%',
            bottom: '3%',
            containLabel: true
        },
        toolbox: {},
        xAxis: {
            type: 'category',
            boundaryGap: false,
            axisLabel: {
                interval:0,
                rotate:35
            },
            data: xaxis
        },
        yAxis: {
            type: 'value'
        },
        series: series
    };
    myChart.setOption(option);
    window.onresize = function () {
        myChart.resize();
    }

}